package com.devenv.common;

import lombok.Data;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Max;

/**
 * 分页请求参数
 * 统一的分页查询参数
 */
@Data
public class PageRequest {
    
    /**
     * 当前页，从1开始
     */
    @Min(value = 1, message = "页码必须大于0")
    private Long current = 1L;
    
    /**
     * 每页大小
     */
    @Min(value = 1, message = "每页大小必须大于0")
    @Max(value = 1000, message = "每页大小不能超过1000")
    private Long size = 10L;
    
    /**
     * 排序字段
     */
    private String sortField;
    
    /**
     * 排序方向：asc/desc
     */
    private String sortOrder = "desc";

    /**
     * 转换为Spring Data的Pageable
     */
    public org.springframework.data.domain.Pageable toPageable() {
        org.springframework.data.domain.Sort sort = org.springframework.data.domain.Sort.unsorted();
        
        if (sortField != null && !sortField.trim().isEmpty()) {
            org.springframework.data.domain.Sort.Direction direction = 
                "asc".equalsIgnoreCase(sortOrder) ? 
                org.springframework.data.domain.Sort.Direction.ASC : 
                org.springframework.data.domain.Sort.Direction.DESC;
            
            sort = org.springframework.data.domain.Sort.by(direction, sortField);
        }
        
        return org.springframework.data.domain.PageRequest.of(
            Math.toIntExact(current - 1), // Spring Data页码从0开始
            Math.toIntExact(size),
            sort
        );
    }

    /**
     * 获取偏移量
     */
    public long getOffset() {
        return (current - 1) * size;
    }
}
